<template>
	<!--表格单选-->
	<el-row class="shopUser">
  		<el-col :span="24">
  			<!--查询过滤条件-->
  			<el-form :inline="true" :model="conditionForm" ref="conditionForm" label-width="82px">
  				<!-- <el-form-item label="名称">				
					<el-input v-model="conditionForm.name"></el-input>
				</el-form-item>
				<el-button type="primary" size="small" icon="search" @click="queryTableData">查询</el-button> -->
			</el-form>
  		</el-col>
  		<el-col :span="24">
  			<!--表格数据展示-->
  			<div>
	  			<el-button type="primary" size="small" icon="plus" v-on:click="addFn">新增</el-button>
	  			<el-button type="primary" size="small" icon="edit" v-on:click="editFn">修改</el-button>
	  			<el-button type="primary" size="small" icon="delete" v-on:click="deleteFn">删除</el-button>
				<el-button type="success" size="small" icon="edit" v-on:click="couponEditFn">优惠券</el-button>
				<el-button type="success" size="small" icon="edit" v-on:click="cartShowFn">购物车</el-button>
  			</div>
  			<div class="data-list">
				<m-table-complex :tableDatas="tableDatalist" :queryTableDataUrl="urlPaths.queryList" :queryTableDataParms="conditionForm" :tableColumn="tableColumn"
					ref="tableChild" :isPageByServerSide="true" @select-rowidx-handler="handleCurrentChange" @tableDatas-handler="handleTableDatas">
				</m-table-complex>
			</div>
  		</el-col>
  		<el-col :span="24">
  			<!--新增和修改 dialog-->
			<el-dialog :title="dialogTitle" v-if="dialogVisible" :visible.sync="dialogVisible">
				<el-form :model="configform" ref="configform" :rules="rules" label-width="100px">
					<m-dialog-form-item v-for="column in tableColumn" :configform="configform" :columnInfo="column"
						:uploadImgAttr="uploadDatas">
					</m-dialog-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="closeDialog">取 消</el-button>
					<el-button type="primary" @click="saveSubmit">确 定</el-button>
				</div>
			</el-dialog>
		</el-col>
		<el-col :span="24">
			<!--客户优惠劵管理 dialog-->
			<el-dialog title="客户优惠劵" :visible.sync="editCouponDialogVisible" customClass="customStyle">
				<div>
					<el-button type="primary" size="small" icon="plus" v-on:click="addCoupon">新增</el-button>
					<el-button type="primary" size="small" icon="delete" v-on:click="deleteCoupon">删除</el-button>
				</div>
				<el-table :data="userCoupons" style="width: 100%" highlight-current-row @current-change="handleCurrentCouponChange">
					<el-table-column width="50">
						<template slot-scope="scope">
							<label class="radio">
								<input type="radio" value="2" name="radio" :data-index="scope.row.index">
								<span class="dot"></span>
							</label>
						</template>
					</el-table-column>
					<el-table-column label="id" v-if="false">
						<template slot-scope="scope">
							<el-input v-model="scope.row.id" readonly></el-input>
						</template>
					</el-table-column>
					<el-table-column label="优惠劵">
						<template slot-scope="scope">
							<el-input v-model="scope.row.couponId" :label="findCouponNameById(scope.row.index, scope.row.couponId)" placeholder="全数字ID号"></el-input>
							<span v-if="scope.row.isCouponNameError"><font color="red">请输入正确的优惠劵ID号</font></span>
							<!-- <el-input v-model="scope.row.couponId" :label="findCouponNameById(scope.row.index, scope.row.couponId)" placeholder="全数字ID号"></el-input>
							<font color="red"><span v-if="scope.row.isCouponNameError">请输入正确的优惠劵ID号</span></font> -->
							<!-- <el-select v-model="scope.row.couponId" filterable placeholder="请选择">
								<el-option v-for="item in getSelect(name)" :key="item.id" :label="item.name" :value="item.id"></el-option>
							</el-select> -->
						</template>
					</el-table-column>
					<el-table-column label="优惠劵名称">
						<template slot-scope="scope">
							<el-input v-model="scope.row.couponName"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="优惠劵数量">
						<template slot-scope="scope">
							<el-input-number v-model="scope.row.couponNumber" :min="1"></el-input-number>
						</template>
					</el-table-column>
					<el-table-column label="用户" v-if="false">
						<template slot-scope="scope">
							<el-input v-model="scope.row.userId" readonly></el-input>
						</template>
					</el-table-column>
					<el-table-column label="使用时间">
						<template slot-scope="scope">
							<el-input v-model="scope.row.usedTime"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="交易订单ID">
						<template slot-scope="scope">
							<el-input v-model="scope.row.orderId" readonly></el-input>
						</template>
					</el-table-column>
				</el-table>
				<div slot="footer" class="dialog-footer">
					<el-button type="primary" @click="couponSaveSubmit">确 定</el-button>
				</div>
			</el-dialog>
		</el-col>
		
		<el-col :span="24">
			<!--客户购物车展示 dialog-->
			<el-dialog title="客户购物车" :visible.sync="cartShowDialogVisible" customClass="customStyle">
				<el-table :data="userCart" style="width: 100%" highlight-current-row>
					<el-table-column label="id" v-if="false">
						<template slot-scope="scope">
							<el-input v-model="scope.row.id" readonly></el-input>
						</template>
					</el-table-column>
					<el-table-column label="产品名称">
						<template slot-scope="scope">
							<img :src="scope.row.listPicUrl" :alt="scope.row.goodsName" style="width: 70px;height: 70px">
						</template>
					</el-table-column>
					<el-table-column label="产品名称">
						<template slot-scope="scope">
							<el-input v-model="scope.row.goodsName" readonly></el-input>
						</template>
					</el-table-column>
					<el-table-column label="数量">
						<template slot-scope="scope">
							<el-input v-model="scope.row.number" readonly></el-input>
						</template>
					</el-table-column>
					<el-table-column label="产品特性">
						<template slot-scope="scope">
							<el-input v-model="scope.row.goodsSpecifitionNameValue" readonly></el-input>
						</template>
					</el-table-column>
					<el-table-column label="价格">
						<template slot-scope="scope">
							<el-input v-model="scope.row.retailPrice" readonly></el-input>
						</template>
					</el-table-column>
				</el-table>
				<div slot="footer" class="dialog-footer">
					<el-button type="primary" @click="cartShowDialogVisible=false">确 定</el-button>
				</div>
			</el-dialog>
		</el-col>
	</el-row>
</template>
<script>
	import {
		Message
	} from 'element-ui';
	import store from '../../store';
	import qs from 'qs'
	export default {
		components:{},
		data() {
			return {
				tableDatalist:[],
				conditionForm: { //查询过滤的条件
					name:''
				},
				pagination:{
					totalSize:0,
					pageSize: 20,
					currentPage:1,
				},
				tableColumn:[ 
					{
						columnName:'id', //主键字段，修改和删除的依赖列
						columnLabel:'ID',
						isColumnShow:false, //是否在table表格里显示
						isModifyDialogEnabled:false, //是否在新增或修改对话框中显示该属性字段
					},
					{
						columnName:'username',
						columnLabel:'账号名',
						isColumnShow:false, //是否在table表格里显示
						isModifyDialogEnabled:true, //是否在新增或修改对话框中显示该属性字段
					},
					{
						columnName:'avatar',
						columnLabel:'用户头像',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true,
						isPicColumn:true,
					},
					{
						columnName:'nickname',
						columnLabel:'用户昵称',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'password',
						columnLabel:'账号密码',
						isColumnShow:false, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'gender',
						columnLabel:'性别',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'cartNumber',
						columnLabel:'购物车数量',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:false,
						type:'queryData',
						datas:0
					},
					{
						columnName:'birthday',
						columnLabel:'生日',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'registerTime',
						columnLabel:'注册时间',
						isColumnShow:false, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'registerIp',
						columnLabel:'注册IP',
						isColumnShow:false, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'lastLoginTime',
						columnLabel:'上次登录时间',
						isColumnShow:false, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'lastLoginIp',
						columnLabel:'上次登录IP',
						isColumnShow:false, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'userLevalId',
						columnLabel:'账号用户级别',
						isColumnShow:false, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'mobile',
						columnLabel:'电话',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true,
					},
					{
						columnName:'weixinOpenid',
						columnLabel:'用户微信账号',
						isColumnShow:true, //是否在table表格里显示
						isModifyDialogEnabled:true,
					}
				],
				urlPaths:{
					queryList:'user/listAll',
					delByKey:'user/delete',
					insert:'user/add',
					updateByKey:'user/update',
					queryCouponById:'coupon/queryById',
					// queryCoupon:'coupon/selectByUser',
					queryCoupon:'user/selectCoupons',
					editCoupon:'coupon/editCoupon',
					queryCart:'user/selectCarts',
				},
				configform: {},
				index: '',
				dialogVisible: false,
				dialogTitle:'新增',
				rules: {},
				currentRow: null,
				uploadImgs: {},
				uploadDatas:{
					clazz:'user',
					columnName:''
				},
				isCouponWarn:'',
				editCouponDialogVisible:false,
				userCoupons:[],
				selectedCoupon:'',
				cartShowDialogVisible:false,
				allUserCarts:{},
				userCart:[],
			}
		}, 
		computed:{
		},
		watch:{
// 			tableDatalist:{
// 				handler: function (newVal,oldVal){
// 					debugger;
// 					if (newVal!=undefined && newVal.length>0){
// 						for(var data of newVal){
// 							this.$httpExt().get(this.urlPaths.queryCart, {
// 								userId:data.id
// 							}).then((response) => {
// 								if(response.succ == 'ok') {
// 									var rows= response.rows;
// 									this.allUserCarts[data.id]=rows;
// 									data.cartNumber = response.totalSize;
// 									console.log('cart number:'+response.totalSize);
// 								}
// 							}, (data) => {
// 								Message({
// 									message: data.msg ? data.msg : '服务器请求失败，请重试！',
// 									type: 'warning'
// 								});
// 							});
// 						}
// 					}
// 				}
			// }
		},
    	mounted() {
    		this.initData();
		},
		methods: {
			initData(){
			},
			queryTableData(){
				this.$refs.tableChild.initData();
			},
			/*选择一条数据*/
			handleCurrentChange(val) {
				if(!val) {
					return
				}
				this.currentRow = val;
				this.index = val.index+''
				console.log('this.currentRow ',this.currentRow);
				console.log('this.index ',this.index);
			},
			/*新增*/
			addFn(){
				this.dialogVisible = true;
				this.dialogTitle='新增';
				/*if(this.$refs['configform']!=undefined) {
					this.$refs['configform'].resetFields();
				}*/
				this.setFormData();
			},
			/*编辑*/
			editFn(){
				if(this.index) {
					this.dialogVisible = true;
					this.dialogTitle='编辑';
					this.setFormData();
				}else{
					Message({
						message: '请选择一条进行操作！',
						type: 'warning'
					});
				}
			},
			setFormData(){
				var form ={};
				for(let col of this.tableColumn){
					if (this.dialogTitle=='新增'){
						if (col.defaultValue != undefined && col.defaultValue!=''){
							form[col.columnName] = col.defaultValue;
						} else {
							form[col.columnName] = '';
						}
					} else {
						form[col.columnName] = this.currentRow[col.columnName];
					}
				}
				this.configform = form;
			},
			/*删除*/
			deleteFn(){
				if(this.index) {
					this.$confirm('你确定要删除吗？', '删除提示', {
			          	confirmButtonText: '确定',
			          	cancelButtonText: '取消',
			          	type: 'warning'
			        }).then(() => {
			        	//调删除接口
			        	this.$httpExt().get(this.urlPaths.delByKey, {
							id:this.currentRow.id
						}).then((response) => {
//							Message({
//								message: response.msg,
//								type: 'success'
//							});
							this.queryTableData();
						},(response) => {
							Message({
								message: '服务器请求失败，请重试！',
								type: 'warning'
							});
						});
			        });
				}else{
					Message({
						message: '请选择一条进行操作！',
						type: 'warning'
					});
				}
			},
			/*提交*/
			saveSubmit(){				
				var that = this;
				if(this.dialogTitle == '新增') {
//							that.configform.id = '';
					var url = this.urlPaths.insert;
				} else {
					var url = this.urlPaths.updateByKey;
				}
				console.log(url);
				console.log(that.configform);
				this.$httpExt().post(url,that.configform).then((response) => {
					if(response.succ == 'ok') {
						that.queryTableData();
						that.dialogVisible = false;
					}
				}, (data) => {
					Message({
						message: data.msg ? data.msg : '服务器请求失败，请重试！',
						type: 'warning'
					});
				});
			},
			closeDialog(){
				this.dialogVisible = false;
			},
			/*优惠劵编辑*/
			couponEditFn(){
				if(this.index) {
					this.editCouponDialogVisible = true;
					this.userCoupons =[];
					this.$httpExt().get(this.urlPaths.queryCoupon, {
						userId:this.currentRow.id
					}).then((response) => {
						if(response.succ == 'ok') {
							var rows= response.rows;
							console.log(rows);
							for(let [index, item] of rows.entries()){
								item.index = index;
								item.isCouponNameError=false;
							}
							this.userCoupons = rows;
						}
					}, (data) => {
						Message({
							message: data.msg ? data.msg : '服务器请求失败，请重试！',
							type: 'warning'
						});
					});
				}else{
					Message({
						message: '请选择一条进行操作！',
						type: 'warning'
					});
				}
			},
			/*提交*/
			couponSaveSubmit(){
				console.log(this.currentRow);
				console.log(JSON.stringify(this.userCoupons));
				for(let [index, item] of this.userCoupons.entries()){
					if (item.isCouponNameError===true || item.couponId==''){
						return;
					}
				}
				this.$httpExt().post(this.urlPaths.editCoupon, qs.stringify({
					coupons: JSON.stringify(this.userCoupons),
					userId: this.currentRow.id,
				})).then((response) => {
					if(response.succ == 'ok') {
						this.editCouponDialogVisible=false;
					} else {
						Message({
							message: response.msg ? response.msg : '服务器操作失败，请重试！',
							type: 'warning'
						});
					}
				}, (data) => {
					Message({
						message: data.msg ? data.msg : '服务器请求失败，请重试！',
						type: 'warning'
					});
				});
			},
			addCoupon(){
				var elem = {}
				elem['id'] = 0;
				elem['couponId'] = '';
				elem['couponNumber'] = 1;
				elem['userId'] = this.currentRow.id;
				elem['usedTime'] = '';
				elem['orderId'] = '';
				elem['isCouponNameError'] = false;
				this.userCoupons.push(elem);
				for(let [index, item] of this.userCoupons.entries()){
					item.index = index;
				}
			},
			cartShowFn(){
				if(this.index) {
					this.cartShowDialogVisible = true;
					this.userCart =[];
					console.log(this.allUserCarts);
					if(this.allUserCarts.size >0 && this.allUserCarts[this.currentRow.id]!=undefined){
						this.userCart=this.allUserCarts[this.currentRow.id];
					} else {
						this.$httpExt().get(this.urlPaths.queryCart, {
							userId:this.currentRow.id
						}).then((response) => {
							if(response.succ == 'ok') {
								var rows= response.rows;
								console.log(rows);
		// 							for(let [index, item] of rows.entries()){
		// 								item.index = index;
		// 							}
								this.userCart = rows;
							}
						}, (data) => {
							Message({
								message: data.msg ? data.msg : '服务器请求失败，请重试！',
								type: 'warning'
							});
						});
					}
				}else{
					Message({
						message: '请选择一条进行操作！',
						type: 'warning'
					});
				}
			},
			/*选择一条优惠劵*/
			handleCurrentCouponChange(val) {
				if(!val) {
					return
				}
				this.selectedCoupon= val;
				console.log(this.selectedCoupon);
			},
			deleteCoupon(){
				// console.log(this.userCoupons);
				if(this.selectedCoupon !==undefined || this.selectedCoupon!=='') {
					this.userCoupons.forEach((v, i) => {
						if (this.selectedCoupon.index === v.index) {
							// i 为选中的索引
							this.userCoupons.splice(i, 1);
						}
					});
					this.selectedCoupon='';
				}else{
					Message({
						message: '请选择一条进行操作！',
						type: 'warning'
					});
				}
			},
			findCouponNameById(rowIndex, id){
				if(id ===undefined || id ===''){
					return '';
				}
				var name =id;
				var couponRow = this.userCoupons.find((element) => (element.index === rowIndex));
				this.$httpExt().get(this.urlPaths.queryCouponById, {
					id:id
				}).then((response) => {
					if(response.succ == 'ok') {
						var row= response.result;
						console.log(row);
						name= row.name;
						couponRow.isCouponNameError=false;
					} else {
						couponRow.isCouponNameError=true;
					}
				},(response) => {
					Message({
						message: '服务器请求失败，请重试！',
						type: 'warning'
					});
					couponRow.isCouponNameError=true;
				});
				return name;
			},
			handleReset() {
				this.newlyFormVisible = false
			},
			handleTableDatas(val){
				this.tableDatalist=val;
				console.log('tableDatas is changed');
				if (this.tableDatalist!=undefined && this.tableDatalist.length>0){
					for(var data of this.tableDatalist){
						this.$httpExt().get(this.urlPaths.queryCart, {
							userId:data.id
						}).then((response) => {
							if(response.succ == 'ok') {
								var rows= response.rows;
								var id = response.msg;
								this.$set(this.allUserCarts, id, rows);
								var col = this.tableDatalist.find((element) => (element.id == id));
								col.cartNumber = response.totalSize;
								// this.allUserCarts[id]=rows;
								// data.cartNumber = response.totalSize;
								console.log('cart number:'+response.totalSize);
							}
						}, (data) => {
							Message({
								message: data.msg ? data.msg : '服务器请求失败，请重试！',
								type: 'warning'
							});
						});
					}
				}
			},
	    }
	}
</script>
<style>
.fl{
	float: left;
}
.user a{
	color: #20a0ff;
	text-decoration: none;
}
.customStyle{
    width:80%;
}

</style>